package com.yupi.shortchain.Listener;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.yupi.shortchain.constant.UserConstant;
import com.yupi.shortchain.model.dto.file.DemoData;
import com.yupi.shortchain.model.dto.file.DemoDataDTO;
import com.yupi.shortchain.model.dto.urlrelate.UrlRelateAddRequest;
import com.yupi.shortchain.model.entity.UrlRelate;
import com.yupi.shortchain.model.entity.User;
import com.yupi.shortchain.service.UrlRelateService;
import com.yupi.shortchain.utils.BeanCopyUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

// 有个很重要的点 DemoDataListener 不能被spring管理，要每次读取excel都要new,然后里面用到spring可以构造方法传进去
@Slf4j
public class DemoDataListener implements ReadListener<DemoData> {

    private UrlRelateService urlRelateService;

    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    /**
     * 缓存的数据
     */
    private List<DemoDataDTO> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    /**
     * 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来
     *
     * @param urlRelateService
     */
    public DemoDataListener(UrlRelateService urlRelateService) {
        this.urlRelateService = urlRelateService;
    }

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data    one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(DemoData data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSONUtil.toJsonStr(data));

        log.info("是否登录{}",StpUtil.isLogin());
        //int loginId = (Integer) StpUtil.getLoginId();
        User user = (User) StpUtil.getTokenSession().get(UserConstant.USER_LOGIN_STATE);

        DemoDataDTO dto = new DemoDataDTO();

        dto.setUserId(user.getId());
        // 将长链转化为短链
        String shortUrl = urlRelateService.addUrlRelate(data.getLongUrl());
        dto.setLongUrl(data.getLongUrl());
        dto.setSortUrl(shortUrl);
        cachedDataList.add(dto);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成！");
    }
    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", cachedDataList.size());
        //UrlRelate urlRelate = new UrlRelate();
        List<UrlRelate> urlRelates = BeanCopyUtils.copyBeanList(cachedDataList, UrlRelate.class);
        urlRelateService.saveBatch(urlRelates,100);
        log.info("存储数据库成功！");
    }
}
